class common {

  //转换uint8array
  static file2uint8array(o,type) {
    return new Promise((resolve, reject) => {
      dataURL2Image(o,(c)=>{
        // 清除元数据(BanQuanXinXi)操作
        let a = canvasCompress(c,type)
        for (var b = a.split(","), d = (b[0].match(/:(.*?);/)[1], atob(b[1])), e = d.length, f = new Uint8Array(e); e--;) f[e] = d.charCodeAt(e);
        resolve(f)
      })
    });
  }

  //转换成blob
  static file2blob(a, b) {
    if (b.match(/\.jpeg|\.gif|\.jpg|\.png/)) {
      var c = new Blob([a]),
        d = window.URL.createObjectURL(c);
      return d
    }
  }

  // 图片文件转 Base64 编码
  static file2DataURL(file, callback){
    // console.log(file)
    const reader = new FileReader();
    reader.onload = function (event) {
      const dataURL = this.result;
      callback(dataURL);
    };
    reader.readAsDataURL(file);
  }

  //判断后缀，是否为真实png图片
  static checkPng(data){
    //PNG 文件的前八个字节始终包含以下（十进制）值：137 80 78 71 13 10 26 10
    if(data[0]==137&&data[1]==80&&data[2]==78&&data[3]==71&&data[4]==13&&data[5]==10&&data[6]==26&&data[7]==10){
      return true
    }else {
      return false
    }
  }

  //计算图片size
  static getSize(a, b) {
    var c = b ? 1e3 : 1024;
    if (Math.abs(a) < c) return a + " B";
    var d = b ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"],
        e = -1;
    do a /= c, ++e; while (Math.abs(a) >= c && e < d.length - 1);
    // return a.toFixed(1) + " " + d[e]
    return a.toFixed(1)
  }

  
}

export default common

// dataURL 转 img 对象
const dataURL2Image = (dataURL, callback) => {
  const img = new Image();
  img.onload = () => {
    callback(img);
  };
  img.src = dataURL;
};

// canvas 处理图片，清除图片元数据
const canvasCompress = (img, type) => {
  const canvas = document.createElement('canvas');
  const {
      width,
      height
  } = img;
  canvas.width = width;
  canvas.height = height;

  const context = canvas.getContext('2d');
  context.drawImage(img, 0, 0, width, height);
  const compressedDataURL = canvas.toDataURL(type, 0.1);
  return compressedDataURL;
};